
//KEY是一个常量,所以不用在定义的的函数中作为参数传入
export const KEY ='goodsdata';
// 存储的数据格式goodsdatas  [{"goodsid":0,"count":0}]
export var valueObj={goodsid:0,count:0};
export function setItem(value){
    var JsonStr=localStorage.getItem(KEY)||'[]';
    var arr=JSON.parse(JsonStr);
    arr.push(value);
    localStorage.setItem(KEY,JSON.stringify(arr));
}

export function getItem(){
    var str=localStorage.getItem(KEY)||'[]';
    console.log(str);
    return JSON.parse(str);
}

export function removeItem(KEY){
    
}

export function getGoodsObj(){
    var arr=getItem();
    //合并goodsid相同的数据为一个对象arrObj，形式为{87：1 ，88：2}
    var arrObj={};
    for(var i=0;i<arr.length;i++){
         var item=arr[i];
         if(!arrObj[item.goodsid]){
            arrObj[item.goodsid]=item.count;
         }else{
             var count=arrObj[item.goodsid];
             arrObj[item.goodsid]=count+item.count
         }
    }
     
    return arrObj;
        
}
//更新数据
export function updateObj(obj){
    var arr=getItem();
    var count=1;
    if(obj.type=='add'){
        arr.push({"goodsid":obj.goodsid,"count":count});
        console.log('a');
    }else{
        for(var i=arr.length-1;i>=0;i--){
            if(arr[i].goodsid==obj.goodsid){
                if(arr[i].count>1){
                    arr[i].count--;
                    console.log('a');
                    break;
                }else{
                    //删除此项
                    arr.splice(i,1);
                    console.log('s');
                    break;
                }
            }
        }
    }
    localStorage.setItem(KEY,JSON.stringify(arr));
}
//移除数据
export  function delItem(goodsid){
    var arr=getItem();
    for(var i=arr.length-1;i>=0;i--){
        if(arr[i].goodsid==goodsid){
            arr.splice(i,1);
        }
    }
    localStorage.setItem(KEY,JSON.stringify(arr));
}
